package com.kim.net.impl;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;

import android.util.Log;

import com.kim.net.NetCallback;
import com.kim.net.NetEntity;
import com.kim.net.NetPost;
import com.kim.net.NetUtil;

public class NetPostImp extends NetPost {

	private static final String TAG = "NetPostImp";

	public NetPostImp(NetEntity entity, NetCallback netCallback) {
		super(entity, netCallback);
	}

	@Override
	protected void send() {
		HttpURLConnection httpURLConnection = null;
		InputStream inputStream = null;
		int responseCode = 0;
		try {
			Log.d(TAG, "targetUrl:" + entity.url);
			httpURLConnection = NetUtil.getHttpURLConnection(entity.url,
					entity.headers, entity.getSendData());
			responseCode = httpURLConnection.getResponseCode();
			boolean gzip = false;
			if (HTTP_RESPONSECODE_200 == responseCode) {
				entity.receiveHeaders = httpURLConnection.getHeaderFields();
				inputStream = httpURLConnection.getInputStream();
				String headerStr = entity.receiveHeaders.toString();
				Log.d("NetPostImp", "head:" + headerStr);
				if (headerStr != null) {
					headerStr = headerStr.toUpperCase();
					if (headerStr.indexOf("CONTENT-ENCODING=[GZIP]") != -1) {
						gzip = true;
					}
				}
				netCallback.onSuccess(responseCode, inputStream, entity, gzip);
			} else {
				inputStream = httpURLConnection.getInputStream();
			}
			netCallback.onOtherResponseCode(responseCode, inputStream, entity,
					gzip);
		} catch (IOException e) {
			String errorMsg = "";
			if (e != null) {
				errorMsg = e.getMessage();
			}
			netCallback.onError(responseCode, errorMsg);
			catchException(e);
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (httpURLConnection != null) {
				httpURLConnection.disconnect();
			}
		}
	}

	@Override
	protected void catchException(IOException ex) {
		Log.d(TAG, "Exception:" + ex.getMessage());
	}

}
